package com.calendar.guos.client;



import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.bradrydzewski.gwt.calendar.client.*;
import com.calendar.guos.client.calendar.GcalendarData;
import com.google.gwt.gdata.client.DateTime;
import com.google.gwt.gdata.client.Recurrence;
import com.google.gwt.gdata.client.Where;
import com.google.gwt.gdata.client.atom.Text;

import com.google.gwt.gdata.client.calendar.CalendarEntry;
import com.google.gwt.gdata.client.calendar.CalendarEventEntry;
import com.google.gwt.gdata.client.When;
import com.google.gwt.gdata.client.Where;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;



public class GUoSCalendarEventTranslator {
    /**
     * The available styles that can be applied to appointments when using the
     * the &quot;Google&quot; theme.
     */
    public static final AppointmentStyle[] GOOGLE_STYLES =
            new AppointmentStyle[]{AppointmentStyle.GREEN, AppointmentStyle.BLUE,
    	AppointmentStyle.LIGHT_GREEN, AppointmentStyle.BLUE_GREY};

	public final static DateTimeFormat dtf = DateTimeFormat.getFormat("yyyyMMdd'T'HHmmss");
	
	public enum TimeType
	{
		Single,
		Recurring
	}
	
	public enum Weekdays
	{
		Sunday,
		Monday,
		Tuesday,
		Wednesday,
		Thursday,
		Friday,
		Saturday,
		None
	}
	

	public static ArrayList<Appointment[]> translateCalEventEntryToAppt(GcalendarData gCal, CalendarEntry calendar, CalendarEventEntry[] calendarEvents) {
		ArrayList<Appointment[]> calendarAppts = new ArrayList<Appointment[]>();
		
       
        initializeAppts(calendarAppts, calendarEvents);
        translateEntryAttributes(calendarAppts, calendarEvents);

		
		return calendarAppts;
	}

public static void initializeAppts(ArrayList<Appointment[]> calendarAppts , CalendarEventEntry[] calendarEvents){


    
    for (int i = 0; i < calendarEvents.length; i++) {
   	 
	       CalendarEventEntry entry = calendarEvents[i];
	       
	       When[] times = entry.getTimes();
	  
	    	   calendarAppts.set(i, new Appointment[times.length]);
	       
    }


}

public static Date getDate(DateTime dateToConvert){

	Date rtDate = dateToConvert.getDate();
	
	return rtDate;
}

	public static void translateEntryAttributes(ArrayList<Appointment[]> calendarAppts , CalendarEventEntry[] calendarEvents){
        //Randomly generate styles
		AppointmentStyle style = GOOGLE_STYLES[Random.nextInt(GOOGLE_STYLES.length)];
        Date[] date;

        //Set Dates
	     for (int i = 0; i < calendarEvents.length; i++) {
	    	 
		       CalendarEventEntry entry = calendarEvents[i];
		       
		       When[] times = entry.getTimes();
		       for ( int j = 0; j < times.length; j++){
		    	   
		    	   date = new Date[2];
		    	   date[0] = getDate(entry.getTimes()[j].getStartTime());
		    	   
		    	   date[1] = getDate(entry.getTimes()[j].getEndTime());
		    	   
		    	   //get(Event)[occurence]
		    	   calendarAppts.get(i)[j].setStart(date[0]);
		    	   calendarAppts.get(i)[j].setEnd(date[0]);
		    	   
		    	   System.out.println(date[0]);
		    	   
		    	   
		       }
		       
	     }

		//Set titles 
		for (int i = 0; i < calendarEvents.length; i++) {
		       CalendarEventEntry entry = calendarEvents[i];
		       String title = entry.getTitle().getText();
		       
		       for(int j = 0; j < calendarAppts.get(i).length; j++){
		    	   calendarAppts.get(i)[j].setTitle(title);
		       }
	     }
	     //Set authors
		for (int i = 0; i < calendarEvents.length; i++) {
		       CalendarEventEntry entry = calendarEvents[i];
		       String author = null;
		       
		       for(int k = 0; k < entry.getAuthors().length; k++){
			       author += " " + entry.getAuthors()[k];   
		       }
		       for(int j = 0; j < calendarAppts.get(i).length; j++){
		    	   
		    	   calendarAppts.get(i)[j].setCreatedBy(author);
		       }
	     }
		
		//Set Style
		for (int i = 0; i < calendarEvents.length; i++) {
		       CalendarEventEntry entry = calendarEvents[i];
		       //Randomly generate styles

		       for(int j = 0; j < calendarAppts.get(i).length; j++){
		    	   calendarAppts.get(i)[j].setStyle(style);
		       }
		       
	     }
		//Set descriptions
		for (int i = 0; i < calendarEvents.length; i++) {
		       CalendarEventEntry entry = calendarEvents[i];
		       String description = entry.getContent().toString();

		       for(int j = 0; j < calendarAppts.get(i).length; j++){
		    	   calendarAppts.get(i)[j].setDescription(description);
		       }
		       
	     }
		//Set locations
		for (int i = 0; i < calendarEvents.length; i++) {
		       CalendarEventEntry entry = calendarEvents[i];
		       
		       Where[] locations = entry.getLocations();
		       String location = null;
		       
		       for(int k = 0; k < entry.getLocations().length; k++){
			       location += " "+entry.getLocations()[k];   
		       }
		       for(int j = 0; j < calendarAppts.get(i).length; j++){
		    	   calendarAppts.get(i)[j].setLocation(location);
		       }
		       
	     }

	}


	/*
	 * Used to translate appointments into calendar event entries
	 * Need to specify time type which is either recurring or single
	 */
	public static CalendarEventEntry translateApptToCalEventEntry(Appointment event, TimeType timeType, Weekdays[] interval){
		CalendarEventEntry entry = CalendarEventEntry.newInstance();
		entry.setTitle(Text.newInstance());
		entry.getTitle().setText(event.getTitle());
		
		entry.setContent(Text.newInstance());
		entry.getContent().setText(event.getDescription());
		
		//create entry as recurring time
		if (timeType == TimeType.Recurring)
		{
			//String pattern = "yyyyMMdd'T'HHmmss";
			
			//TODO: use dateFormat
			//DateTimeFormat dtf = DateTimeFormat.getFormat(pattern);
			Date startDate = event.getStart();
			/*
			String startDateString = "" + startDate.getYear();
			startDateString += startDate.getMonth();
			startDateString += startDate.getDay() + "T";
			startDateString += startDate.getHours();
			startDateString += startDate.getMinutes();
			startDateString += startDate.getSeconds();*/
			
			
			Date endDate = event.getStart();
			/*
			String endDateString = "" + endDate.getYear();
			endDateString += endDate.getMonth();
			endDateString += endDate.getDay() + "T";
			endDateString += endDate.getHours();
			endDateString += endDate.getMinutes();
			endDateString += endDate.getSeconds();*/
			
			String icalBreak = "\r\n";
		    String recurrenceString = "DTSTART;TZID=America/Regina:";
		    recurrenceString += dtf.format(startDate) + icalBreak;
		    recurrenceString += "DTEND;TZID=America/Regina:";
		    recurrenceString += dtf.format(endDate) + icalBreak;
		    recurrenceString += "RRULE:FREQ=WEEKLY";
			recurrenceString += ";UNTIL=";
		    recurrenceString += dtf.format(endDate);
		    
		    if (interval.length != 0)
		    {		    	
		    	recurrenceString += ";BYDAY=";
		    	String intervalDay = "";
		    	for (int i = 0; i < interval.length; i++)
		    	{
		    		if (interval[i] == Weekdays.Sunday)
		    		{		    		
		    			intervalDay += "SU";
		    		}
		    		else if (interval[i] == Weekdays.Monday)
		    		{		    		
		    			intervalDay += "MO";
		    		}
		    		else if (interval[i] == Weekdays.Tuesday)
		    		{
		    			intervalDay += "TU";
					}
		    		else if (interval[i] == Weekdays.Wednesday)
		    		{		    		
		    			intervalDay += "WE";
		    		}
		    		else if (interval[i] == Weekdays.Thursday)
		    		{
		    			intervalDay += "TH";
		    		}
		    		else if (interval[i] == Weekdays.Friday)
		    		{
		    			intervalDay += "FR";
		    		}
		    		else if (interval[i] == Weekdays.Saturday)
		    		{
		    			intervalDay += "SA";
		    		}
		    		
	    			if (i + 1 < interval.length)
	    			{
	    				intervalDay += ",";
	    			}
		    	}
		    	
		    	recurrenceString += intervalDay;
		    }
		    			    			
			entry.setRecurrence(Recurrence.newInstance());
			entry.getRecurrence().setValue(recurrenceString);
		}
		//create entry as single time
		else
		{
			When when = When.newInstance();
			when.setStartTime(DateTime.newInstance(event.getStart()));
			when.setEndTime(DateTime.newInstance(event.getEnd()));
			entry.addTime(when);
		}
		
		Where where = Where.newInstance();
		//Location format = "<Building name> - <Floor number> - <Room number>"
		where.setValueString(event.getLocation());
		
		entry.addLocation(where);
		
		return entry;
	}
	
	
	
	
	
}
